package jnpf.service.impl;


import jnpf.base.service.SysconfigService;
import jnpf.permission.entity.UserEntity;
import jnpf.exception.LoginException;
import jnpf.model.login.BaseSystemInfo;
import jnpf.model.password.PassContextHolder;
import jnpf.permission.service.UserService;
import jnpf.util.IpUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private SysconfigService sysconfigService;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) {
        BaseSystemInfo sysConfigInfo = sysconfigService.getSysInfo();
        if (sysConfigInfo==null){
            throw new LoginException("服务正在启动，请稍等");
        }
        //安全验证
        if ("1".equals(sysConfigInfo.getWhitelistSwitch())) {
            List<String> ipList = Arrays.asList(sysConfigInfo.getWhitelistIp().split(","));
            if (!ipList.contains(IpUtil.getIpAddr())) {
                throw new LoginException("此IP未在白名单中，请联系管理员");
            }
        }
        UserDetails user = null;
        UserEntity userEntity = userService.getUserEntity(username);
        Collection<SimpleGrantedAuthority> list = new ArrayList();
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("aa");
        list.add(simpleGrantedAuthority);
        user = new User(username, userEntity.getPassword(), list);
        PassContextHolder.setUserName(username);
        return user;
    }

}
